<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Http\Requests\Admin\DocumentOrderExpressRequest;
use App\Models\DocumentOrder;
use App\Models\Order;
use App\Service\Wechat\WechatPayService;
use Carbon\Carbon;
use EasyWeChat\Kernel\Exceptions\InvalidConfigException;
use Exception;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class DocumentOrderController extends AdminBaseController
{
    /**
     * Display a listing of the resource.
     *
     * @return JsonResponse|object
     */
    public function index()
    {
        $list = DocumentOrder::filter(\request()->all())
            ->select([
                'qh_document_orders.*',
                'user.id as userId',
                'user.nickname as userNickname',
                'user.avatar as userAvatar',
                'user.mobile as userMobile',
                'qh_documents.title as documentTitle',
            ])
            ->join('user', 'qh_document_orders.userId', '=', 'user.id')
            ->join('qh_documents', 'qh_document_orders.documentId', '=', 'qh_documents.id')
            ->orderByDesc('id')
            ->paginateFilter(\request('perPage', 10));

        return $this->restful($list);
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param int $id
     * @return JsonResponse|object
     */
    public function destroy(int $id)
    {
        $order = DocumentOrder::findOrFail($id);
        $order->delete();

        return $this->restful();
    }

    /**
     * 退款
     * @param $id
     * @param WechatPayService $wechatPayService
     * @return JsonResponse|object
     * @throws InvalidConfigException
     * @throws Exception
     */
    public function refund($id, WechatPayService $wechatPayService) {
        $order = DocumentOrder::findOrFail($id);
        if ($order->status != 2 && $order->status != 5) throw new Exception('该状态不支持退款');

        $refundTradeNo = 'REFUND'.time().rand(1000, 9999);
        $order->refundTradeNo = $refundTradeNo;
        $order->save();

        $result = $wechatPayService->refundByDocumentOrder($order);

        if (!$result) {
            return $this->restful(null, false, '退款申请失败');
        }

        return $this->restful(true, '退款申请成功');
    }

    /**
     * 发货
     * @param DocumentOrderExpressRequest $request
     * @return JsonResponse|object
     */
    public function express(DocumentOrderExpressRequest $request) {
        $params = $request->validated();

        $order = DocumentOrder::findOrFail($params['id']);
        if (empty($order->sendAt)) {
            $order->sendAt = Carbon::now();
        }
        $order->address = $params['address'];
        $order->express = $params['express'];
        $order->status = 5; // 已发货

        $order->save();

        return $this->restful();
    }
}
